<template>
  <div class="app-container">
    <el-form ref="elForm" :model="formData" :disabled="$route.query.isInfo || isInfo" :rules="rules" size="medium"
      label-width="100px">
      <h2 style="text-align: center">费用报销</h2>
      <h4 class="form-header h4">基本信息</h4>
      <el-row :gutter="15">
        <el-col :span="6">
          <el-form-item label="报销编号" prop="feeNo">
            <el-input v-model="formData.feeNo" placeholder="保存后自动生成" :disabled="true" clearable
              :style="{ width: '100%' }"></el-input>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="6">
          <el-form-item label="报销名称" prop="feeName">
            <el-input
              v-model="formData.feeName"
              placeholder="请输入报销名称"
              clearable
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
        </el-col> -->
        <el-col :span="6">
          <el-form-item label="报销类型" prop="payTypeValue">
            <el-select v-model="formData.payTypeValue" filterable placeholder="请选择报销类型">
              <el-option v-for="dict in dict.type.sys_fee_type" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>

        <!-- <el-col :span="6">
          <el-form-item label="申请总额" prop="totalFee">
            <el-input
              v-model="formData.totalFee"
              placeholder="请输入申请总额"
              clearable
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
        </el-col> -->
        <!-- <el-col :span="6">
          <el-form-item label="所属项目" prop="projectName">
            <el-select
              :style="{ width: '100%' }"
              v-model="formData.projectName"
              filterable
              placeholder="请选择所属项目"
            >
              <el-option
                v-for="dict in projectList"
                :key="dict.projectId"
                :label="dict.projectName"
                :value="dict.projectName"
              />
            </el-select>
          </el-form-item>
        </el-col> -->
        <el-col :span="6">
          <el-form-item label="填报人" prop="applyUserId">
            <!-- <UserDialog
              :typeValue="formData.deptId"
              placeholder="请输入填报人"
              @change="changeUser"
              v-model="formData.applyUserId"
            ></UserDialog> -->
            <el-input v-model="formData.applyUserName" placeholder="请输入填报人" :disabled="true" clearable
              :style="{ width: '100%' }"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="部门" prop="deptName">
            <el-input v-model="formData.deptName" placeholder="请输入部门" :disabled="true" clearable
              :style="{ width: '100%' }"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="领款人" :prop="formData.payTypeValue == '0' ? 'receiverUserId' : ''">
            <UserDialog placeholder="请输入领款人" @change="changeUser" v-model="formData.receiverUserId"></UserDialog>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" type="textarea" placeholder="请输入多行文本备注" :autosize="{ minRows: 4, maxRows: 4 }"
          :style="{ width: '100%' }"></el-input>
      </el-form-item>

      <h4 class="form-header h4">发票及附件</h4>
      <el-form-item label="" prop="oss">
        <FileUploadBase :isDelete="!($route.query.isInfo || isInfo)" v-model="formData.oss"></FileUploadBase>
      </el-form-item>
      <h4 class="form-header h4">
        费用报销明细
        <el-button type="primary" plain size="mini" @click="handleAdd">增行</el-button>
        <el-button type="danger" plain size="mini" @click="handleDele">删行</el-button>
      </h4>
      <el-table :data="formData.details" :border="true" style="width: 100%">
        <el-table-column label="序号" type="index" align="center" />
        <el-table-column label="用途" align="center">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`details.${scope.$index}.subjectValue`" :rules="rules.subjectValue">
              <el-input v-model="scope.row.subjectValue" placeholder="请输入用途"></el-input>
              <!-- <el-select
                v-model="scope.row.subjectValue"
                filterable
                placeholder="请选择用途"
              >
                <el-option
                  v-for="dict in dict.type.sys_fee_subject"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select> -->
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="金额" align="center">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`details.${scope.$index}.fee`" :rules="rules.fee">
              <el-input v-model="scope.row.fee" placeholder="请输入金额"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="发票号码" align="center">
          <template slot-scope="scope">
            <el-form-item label-width="0" :prop="`details.${scope.$index}.info`" :rules="rules.info">
              <el-input v-model="scope.row.info" placeholder="请输入发票号码"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
      </el-table>
      <el-row style="margin-top: 20px">
        <el-col :span="8">
          <el-form-item label="本次报销金额">
            <el-input disabled v-model="totalFee" placeholder="本次报销金额"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="金额大写">
            <el-input disabled v-model="formData.chineseFee" placeholder="金额大写"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-col :span="24">
        <el-form-item label-width="0" style="text-align: center; margin-top: 30px">
          <el-button v-if="!($route.query.isInfo || isInfo)" type="primary" @click="submitForm">提交</el-button>
          <el-button :disabled="false" @click="resetForm">返回</el-button>
        </el-form-item>
      </el-col>
    </el-form>
  </div>
</template>

<script>
import store from "@/store";

import {
  getuser,
  feeAdd,
  updateFee,
  infoFee,
} from "@/api/finance/bxgl/index.js";
import { listSelect } from "@/api/business/project.js";
import Cookies from "js-cookie";
export default {
  name: "AddBxgl",
  components: {},
  dicts: ["sys_fee_subject", "sys_fee_type"],

  props: {
    isInfo: {
      type: Boolean,
      default: false,
    },
    id: {
      type: String,
      default: "",
    },
    btnShow: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      totalFee: 0,
      name: store.getters.name,
      projectList: [],
      formData: {
        feeNo: undefined,
        feeName: undefined,
        payTypeValue: undefined,
        totalFee: undefined,
        projectName: undefined,
        deptName: undefined,
        receiverUserId: undefined,
        receiverUserName: undefined,
        applyUserId: "",
        details: [{ fee: "", info: "", subjectValue: "" }],
      },
      rules: {
        payTypeValue: [
          {
            required: true,
            message: "请选择报销类型",
            trigger: "change",
          },
        ],
        receiverUserId: [
          {
            required: true,
            message: "请选择填报人",
            trigger: "change",
          },
        ],
        subjectValue: [
          {
            required: true,
            message: "请选择费用科目",
            trigger: "change",
          },
        ],
        fee: [
          {
            required: true,
            message: "请输入金额",
            trigger: "blur",
          },
        ],
        info: [
          {
            required: true,
            message: "请输入费用详细",
            trigger: "blur",
          },
        ],
        remark: [
          {
            required: false,
            message: "请输入多行文本备注",
            trigger: "blur",
          },
        ],
        oss: [
          {
            required: false,
            message: "附件不能为空",
            trigger: "change",
          },
        ],

        feeNo: [],
        feeName: [
          {
            required: true,
            message: "请输入报销名称",
            trigger: "blur",
          },
        ],
        totalFee: [
          {
            required: true,
            message: "请输入申请总额",
            trigger: "blur",
          },
        ],
        projectName: [
          {
            required: true,
            message: "请输入所属项目",
            trigger: "blur",
          },
        ],
        deptName: [],
        name: [],
      },
    };
  },
  computed: {},
  watch: {
    "formData.details": {
      deep: true,
      handler: function (newVal, oldVal) {
        let num = 0;
        newVal.forEach((i) => {
          if (i.fee && !isNaN(Number(i.fee))) {
            num += Number(i.fee);
          } else {
            num += 0;
          }
        });
        this.totalFee = (Math.round(num * 100) * 1000) / 1000 / 100;
        this.formData.chineseFee = this.convertCurrency(this.totalFee);
        console.log(this.convertCurrency(this.totalFee));
      },
    },
  },
  created() {
    console.log(this.$route.query, '+++++++++++++++++++++++++++++++++>');
    this.$route.query.finished = this.$route.query.finished ? JSON.parse(this.$route.query.finished) : undefined
    if (this.$route.query.finished) {
      this.$route.query.isEdit = JSON.parse(this.$route.query.isEdit)
      this.$route.query.isInfo = JSON.parse(this.$route.query.isInfo)
      console.log(this.$route.query.isEdit, this.$route.query.isInfo);
      console.log(this.$route.query.isEdit, this.$route.query.isInfo);
    }
    if (this.$route.query.isEdit || this.$route.query.isInfo || this.isInfo ) {
      this.getinfo();
    }
    this.getUser();
    this.listSelect();
    this.formData.applyUserName = this.$store.state.user.nickName
    this.formData.applyUserId = this.$store.state.user.id;
    this.formData.deptName = this.$store.state.user.dept.deptName;
    this.formData.deptId = this.$store.state.user.dept.deptId;
  },
  mounted() {
    // this.formData.createByName = this.$store.state.user.nickName
    // this.formData.applyUserId = this.$store.state.user.id

  },
  methods: {
    convertCurrency(money) {
      //汉字的数字
      var cnNums = new Array(
        "零",
        "壹",
        "贰",
        "叁",
        "肆",
        "伍",
        "陆",
        "柒",
        "捌",
        "玖"
      );
      //基本单位
      var cnIntRadice = new Array("", "拾", "佰", "仟");
      //对应整数部分扩展单位
      var cnIntUnits = new Array("", "万", "亿", "兆");
      //对应小数部分单位
      var cnDecUnits = new Array("角", "分", "毫", "厘");
      //整数金额时后面跟的字符
      var cnInteger = "整";
      //整型完以后的单位
      var cnIntLast = "元";
      //最大处理的数字
      var maxNum = 999999999999999.9999;
      //金额整数部分
      var integerNum;
      //金额小数部分
      var decimalNum;
      //输出的中文金额字符串
      var chineseStr = "";
      //分离金额后用的数组，预定义
      var parts;
      // 传入的参数为空情况
      if (money == "") {
        return "";
      }
      money = parseFloat(money);
      if (money >= maxNum) {
        return "";
      }
      // 传入的参数为0情况
      if (money == 0) {
        chineseStr = cnNums[0] + cnIntLast + cnInteger;
        return chineseStr;
      }
      // 转为字符串
      money = money.toString();
      // indexOf 检测某字符在字符串中首次出现的位置 返回索引值（从0 开始） -1 代表无
      if (money.indexOf(".") == -1) {
        integerNum = money;
        decimalNum = "";
      } else {
        parts = money.split(".");
        integerNum = parts[0];
        decimalNum = parts[1].substr(0, 4);
      }
      //转换整数部分
      if (parseInt(integerNum, 10) > 0) {
        let zeroCount = 0;
        let IntLen = integerNum.length;
        for (let i = 0; i < IntLen; i++) {
          let n = integerNum.substr(i, 1);
          let p = IntLen - i - 1;
          let q = p / 4;
          let m = p % 4;
          if (n == "0") {
            zeroCount++;
          } else {
            if (zeroCount > 0) {
              chineseStr += cnNums[0];
            }
            zeroCount = 0;
            chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
          }
          if (m == 0 && zeroCount < 4) {
            chineseStr += cnIntUnits[q];
          }
        }
        // 最后+ 元
        chineseStr += cnIntLast;
      }
      // 转换小数部分
      if (decimalNum != "") {
        let decLen = decimalNum.length;
        for (let i = 0; i < decLen; i++) {
          let n = decimalNum.substr(i, 1);
          if (n != "0") {
            chineseStr += cnNums[Number(n)] + cnDecUnits[i];
          }
        }
      }
      if (chineseStr == "") {
        chineseStr += cnNums[0] + cnIntLast + cnInteger;
      } else if (decimalNum == "") {
        chineseStr += cnInteger;
      }

      return chineseStr;
    },
    changeUser(e) {
      console.log(e);
      this.formData.receiverUserName = e.nickName;
    },
    changeFeeNum(e, i) {
      console.log(e);
      if (!e) return
      let num = Number(e).toFixed(2)
      setTimeout(() => {
        this.formData.details[i].fee = num
      }, 1000)
      console.log(this.formData.details[i].fee);
    },
    handleAdd() {
      this.formData.details.push({ fee: "", info: "", subjectValue: "" });
    },
    handleDele() {
      if (this.formData.details.length == 1) return;
      this.formData.details.pop();
    },
    getinfo() {
      return infoFee(this.$route.query.id || this.id).then((response) => {
        console.log(response);
        this.formData = response.data;
      });
    },
    getUser() {
      getuser(store.state.user.id).then((response) => {
        this.formData.deptName = response.data.user.dept.deptName;
        this.formData.deptId = response.data.user.dept.deptId;
      });
    },
    listSelect() {
      listSelect().then((response) => {
        this.projectList = response.data;
      });
    },
    submitForm() {
      console.log(this.formData);
      this.$refs["elForm"].validate((valid) => {
        if (valid) {
          // console.log(this.totalFee,this.formData.totalFee)
          // if (this.totalFee !== Number(this.formData.totalFee)) {
          //   this.$modal.msgWarning("申请总额不一致");
          //   return;
          // }
          let query = JSON.parse(JSON.stringify(this.formData));
          query.totalFee = this.totalFee
          query.receiverUserName = !query.receiverUserName ? null : query.receiverUserName
          query.receiverUserId = !query.receiverUserId ? null : query.receiverUserId

          query.payTypeLabel = this.dict.type.sys_fee_type.find(
            (i) => i.value === this.formData.payTypeValue
          ).label;
          if (this.formData.compFeeId != undefined) {
            // 如果是代办 点击办理进来 的 将状态改为草稿
            if (this.$route.query.isEdit && !this.$route.query.isInfo) {
              query.status = 'draft'
              query.taskId = this.$route.query.taskId
            }
            updateFee(query).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.resetForm();
            });
          } else {
            feeAdd(query).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.resetForm();
            });
          }
        }
      });
    },
    resetForm() {
      const obj = { path: "./bxgl" };
      this.$tab.closeOpenPage();
    },
  },
};
</script>
